package de.au.fi.domain;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EntityHelper {

	static Logger log = LoggerFactory.getLogger(EntityHelper.class);

	/**
	 * writes all values which are null in new stock and not null in old stock
	 * to new stock.
	 * 
	 * @param stockNew
	 * @return
	 */
	public static <T> T synchronizeObjects(T neww, T old) {
		for (Method method : neww.getClass().getMethods()) {
			if (method.getName().indexOf("get") != -1) {

				try {
					Object value = method.invoke(neww, null);
					if (value == null) {
						value = method.invoke(old, null);
						if (value != null) {
							getSetterForGetter(method).invoke(neww, value);
							log.debug("wrote {} on method {} to new stock",
									value, method.getName());
						}

					}
				} catch (Exception e) {
				}
			}
		}
		return neww;
	}

	public static Method getSetterForGetter(Method getter) {
		for (Method method : getter.getDeclaringClass().getMethods()) {
			if (method.getName().indexOf(getter.getName().substring(3)) != -1
					&& method.getName().startsWith("set")) {
				return method;
			}
		}
		return null;
	}

	public static <T> String log(T object) {
		StringBuffer sb = new StringBuffer();
		for (Method method : object.getClass().getMethods()) {
			if (method.getName().indexOf("get") != -1) {
				sb.append(method.getName().replace("get", ""));
				sb.append(" is ");
				try {
					sb.append(method.invoke(object, null));
				} catch (IllegalArgumentException e) {
				} catch (IllegalAccessException e) {
				} catch (InvocationTargetException e) {
				}
				sb.append(" ");
			}
		}
		return sb.toString();
	}

	public static String getIdForObject(Object object) {
		for (Method method : object.getClass().getMethods()) {
			if (method.getName().equals("getId"))
			{
				try {
					return (String)method.invoke(object, null);
				} catch (Exception e) {
					log.error("Could not get Id for {}", object);
				}
			}
		}
		return null;
	}
}
